class EventEmitter {
  #maxListeners = -1;
  #events = {};
  constructor(maxListeners = -1) {
    this.#maxListeners = maxListeners; // 最大监听数 -1 不限制
  }
  get eventNames() {
    return Object.keys(this.#events);
  }
  /**
   * 监听
   * @param {string} event
   * @param {Function} handler
   */
  on(event, handler) {
    if (!this.#events[event]) {
      this.#events[event] = [];
    }
    // 最大监听数
    if (
      this.#maxListeners !== -1 &&
      this.#events[event].length > this.#maxListeners
    ) {
      return;
    }
    if (!this.#events[event].includes(handler)) {
      this.#events[event].push(handler);
    }
  }
  /**
   * 解除
   * @param {string} event
   * @param {Function?} handler
   */
  off(event, handler) {
    if (!this.#events[event]) return;
    if (!handler) {
      delete this.#events[event];
    } else {
      this.#events[event] = this.#events[event].filter(
        (h) => h !== handler && h._original !== handler
      );
    }
  }
  /**
   * 监听一次
   * @param {string} event
   * @param {Function} handler
   */
  once(event, handler) {
    const onceHandler = (...args) => {
      handler(...args);
      this.off(event, onceHandler);
    };
    // 原始引用
    onceHandler._original = handler;
    this.on(event, onceHandler);
  }
  /**
   * 触发
   * @param {*} event
   * @param  {...args} args
   */
  emit(event, ...args) {
    if (!(event in this.#events)) {
      return;
    }
    const handlers = this.#events[event].slice(); // 创建副本
    for (const handler of handlers) {
      handler(...args);
    }
  }
}

const eventEmitter = new EventEmitter();
console.log(eventEmitter);
export { EventEmitter };
export default eventEmitter;
